package com.hk.kindheartedness;

import androidx.annotation.NonNull;
import androidx.annotation.RequiresApi;
import androidx.appcompat.app.AppCompatActivity;
import androidx.viewpager.widget.PagerAdapter;
import androidx.viewpager.widget.ViewPager;

import android.annotation.SuppressLint;
import android.app.ActivityGroup;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import android.widget.Toast;

import com.google.android.material.bottomnavigation.BottomNavigationItemView;
import com.google.android.material.bottomnavigation.BottomNavigationMenuView;
import com.google.android.material.bottomnavigation.BottomNavigationView;
import com.hk.kindheartedness.util.ToastUtil;

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

/**
 * 患者业务处理
 */
public class PatientMainActivity extends ActivityGroup {

    //    Initialize Toast
    private Toast toast;

    //    Initialize intent
    private Intent intent;

    //    定义一个常量，记录两次点击后退按钮的时间差
    private Long exitTime = 0L;

//  底部菜单导航栏
    private BottomNavigationView bottomNavigationView;

//    menuItem负责展现item选中/未选中的样式变化
    private MenuItem menuItem;

    private ViewPager viewPager;

//    用于存储ViewPage下子视图的集合
    private List<View> viewPageList = new ArrayList<>(4);

    @RequiresApi(api = Build.VERSION_CODES.N)
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_patient_main);
//        获取控制权
        bottomNavigationView = findViewById(R.id.bottomNavigationView);
        viewPager = findViewById(R.id.viewPager);
//        这里的底部菜单栏选中事件是让viewPager移动到指定页面
        bottomNavigationViewItem();
//      viewPager的页面切换事件
        // TODO: 2022/3/19 新增4个页面
//        初始化视图
        initView();
        viewPagerItem();
        Intent intent2 = getIntent();
        Bundle bundle = intent2.getExtras();
//        校验是否患者登录
        checkLoginPatient(bundle);
    }

    /**
     * 校验登录用户是否正确
     * @param bundle
     */
    @RequiresApi(api = Build.VERSION_CODES.N)
    private void checkLoginPatient(Bundle bundle) {
        if (Objects.nonNull(bundle)) { // 存在
            String loginType = bundle.getString("loginType");
//            判断是否为患者登录
            if (Objects.nonNull(loginType) && "0".equals(loginType)) {
                toast = ToastUtil.toastHint(this.toast, PatientMainActivity.this, "欢迎登录！");
                return;
            }
//            如果非患者登录会直接跳转到登录页面
            intent = new Intent(PatientMainActivity.this,LoginActivity.class);
            startActivity(intent);
            PatientMainActivity.this.finish();
            return;
        }
//            如果非患者登录会直接跳转到登录页面
        intent = new Intent(PatientMainActivity.this,LoginActivity.class);
        startActivity(intent);
        PatientMainActivity.this.finish();
        return;
    }

    /**
     * 初始化视图
     */
    private void initView() {
//        提取出传递的登录Id
        Intent intent2 = getIntent();
        Bundle bundle = intent2.getExtras();
        Intent intent = new Intent(PatientMainActivity.this, PatientIndexActivity.class);
        intent.putExtras(bundle);
        viewPageList.add(getLocalActivityManager().startActivity("1", intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP)).getDecorView());
        Intent intent1 = new Intent(PatientMainActivity.this, PatientRegistrationActivity.class);
        intent1.putExtras(bundle);
        viewPageList.add(getLocalActivityManager().startActivity("2", intent1.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP)).getDecorView());
        Intent intent3 = new Intent(PatientMainActivity.this, CaseHistoryActivity.class);
        intent3.putExtras(bundle);
        viewPageList.add(getLocalActivityManager().startActivity("3", intent3.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP)).getDecorView());
        this.intent = new Intent(PatientMainActivity.this, PatientPersonActivity.class);
        this.intent.putExtras(bundle);
        viewPageList.add(getLocalActivityManager().startActivity("4", this.intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP)).getDecorView());
        PagerAdapter pagerAdapter = new PagerAdapter() {
            @Override
            public int getCount() {
                return viewPageList.size();
            }

            @Override
            public boolean isViewFromObject(@NonNull View view, @NonNull Object object) {
                return view == object;
            }

            @NonNull
            @Override
            public Object instantiateItem(@NonNull ViewGroup container, int position) {
                container.addView(viewPageList.get(position));

                return viewPageList.get(position);
            }

            @Override
            public void destroyItem(@NonNull ViewGroup container, int position, @NonNull Object object) {
                container.removeView(viewPageList.get(position));
            }
        };
        viewPager.setAdapter(pagerAdapter);
    }

    /**
     * 当前页面与当前底部导航栏一致，选中
     */
    private void viewPagerItem() {
        viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }

            @Override
            public void onPageSelected(int position) {
                if (menuItem != null) {
                    //如果有已选中的item，则取消它的的选中状态
                    menuItem.setChecked(false);
                } else {
                    //如果没有，则取消默认的选中状态（第一个item）
                    bottomNavigationView.getMenu().getItem(0).setChecked(false);
                }
                //让与当前Pager相应的item变为选中状态
                menuItem = bottomNavigationView.getMenu().getItem(position);
                menuItem.setChecked(true);
            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });
    }

    /**
     * 底部导航栏选中页面切换事件
     */
    private void bottomNavigationViewItem() {
        bottomNavigationView.setOnNavigationItemSelectedListener(new BottomNavigationView.OnNavigationItemSelectedListener() {
            @Override
            public boolean onNavigationItemSelected(@NonNull MenuItem item) {
                switch (item.getItemId()){
                    case R.id.index:
                        Log.i("=========","1");
                        viewPager.setCurrentItem(0);
                        break;
                    case R.id.registration:
                        Log.i("=========","2");
                        viewPager.setCurrentItem(1);
                        break;
                    case R.id.caseHistory:
                        Log.i("=========","3");
                        viewPager.setCurrentItem(2);
                        break;
                    case R.id.person:
                        Log.i("=========","4");
                        viewPager.setCurrentItem(3);
                        break;
                }
                return false;
            }
        });
    }

    //    重写onKeyDown()方法来拦截用户单击后退按钮事件
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
//        判断按下的是否为后退按键
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            exit();
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    //    创建退出方法
    private void exit() {
//        判断两次点击的时间差 大于2秒钟
        if ((System.currentTimeMillis() - exitTime) > 2000) {
            toast = ToastUtil.toastHint(this.toast, PatientMainActivity.this, "再按一次退出程序！");
            exitTime = System.currentTimeMillis();
        } else {
//            关闭当前Activity
            finish();
//            关闭程序
            System.exit(0);
        }
    }

}